//import CoreLocation
//import BackgroundTasks
//import CoreMotion
//import UIKit
//
//// https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW11
//// https://www.jianshu.com/p/3f93da0a9ba2
//
//public class LocationManager: NSObject {
//    static let didChangeAuthorizationNotification = Notification.Name("LocationManagerDidChangeAuthorizationNotification")
//    
//    // 单例方法
//    static let shared: LocationManager = LocationManager()
//    
//    private let locationManager: CLLocationManager = CLLocationManager()
//    private let activityManager: CMMotionActivityManager = {
//        let manager = CMMotionActivityManager()
//        // 第一次时申请权限
//        if CMMotionActivityManager.isActivityAvailable() && CMMotionActivityManager.authorizationStatus() == .notDetermined {
//            manager.startActivityUpdates(to: .main) { _ in
//            }
//        }
//        return manager
//    }()
//    private let database = Database()
//    private(set) var lastAuthorizationStatus: CLAuthorizationStatus = .notDetermined
//    var currentAuthorizationStatus: CLAuthorizationStatus {
//        if #available(iOS 14.0, *) {
//            return locationManager.authorizationStatus
//        } else {
//            return CLLocationManager.authorizationStatus()
//        }
//    }
//    
//    // 调用此方法初始化定位功能
//    private override init() {
//        super.init()
//        // https://developer.apple.com/documentation/corelocation/handling_location_updates_in_the_background
//        
//        // 设置代理
//        locationManager.delegate = self
//        // 设置定位精度
//        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
//        // 设置变动幅度
//        locationManager.distanceFilter = 40
//        // 允许后台持续使用定位功能
//        locationManager.allowsBackgroundLocationUpdates = true
//        // 向用户展示后台定位标识
////        locationManager.showsBackgroundLocationIndicator = true
//        // 省电探索，关掉看看
//        locationManager.pausesLocationUpdatesAutomatically = true
//        // 活动类型
//        locationManager.activityType = .fitness
//        
//        lastAuthorizationStatus = currentAuthorizationStatus
//        
//        NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in
//            self?.startMonitoringSignificant(false)
//            LogManager.shared.log("app willEnterForeground\n")
//        }
//        
//        NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: nil) { _ in
//            LogManager.shared.log("app willResignActive\n")
//        }
//        
//        NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { _ in
////            self?.startRequestLocation()
////            self?.startMonitoringSignificant(false)
////            self?.locationManager.stopMonitoringVisits()
//            LogManager.shared.log("app didBecomeActive\n")
//        }
//        
//        NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { [weak self] _ in
////            self?.startRequestLocation(false)
//            self?.startMonitoringSignificant()
////            self?.locationManager.startMonitoringVisits()
//            LogManager.shared.log("app didEnterBackground\n")
//        }
//        
//        NotificationCenter.default.addObserver(forName: UIApplication.willTerminateNotification, object: nil, queue: nil) { [weak self] _ in
////            self?.startRequestLocation(false)
//            self?.startMonitoringSignificant()
////            self?.locationManager.startMonitoringVisits()
//            LogManager.shared.log("app willTerminate\n")
//        }
//    }
//    
//    func checkAndRequestAuthorization() -> Bool {
//        if (CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .notDetermined) {
//            // 没有获取到权限，再次请求授权
//            locationManager.requestWhenInUseAuthorization()
//        } else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
//            locationManager.requestAlwaysAuthorization()
//        } else if CLLocationManager.authorizationStatus() == .authorizedAlways {
//            return true
//        }
//        return false
//    }
//    
//    // 开始获取定位
//    func startRequestLocation(_ start: Bool = true) {
//        if start {
//            locationManager.startUpdatingLocation()
//            LogManager.shared.log("startRequestLocation\n")
//        } else {
//            locationManager.stopUpdatingLocation()
//            LogManager.shared.log("stopUpdatingLocation\n")
//        }
//    }
//    
//    // 后台监控重要位置变化
//    func startMonitoringSignificant(_ start: Bool = true) {
//        if start {
//            locationManager.startMonitoringSignificantLocationChanges()
//            LogManager.shared.log("startMonitoringSignificant\n")
//        } else {
//            locationManager.stopMonitoringSignificantLocationChanges()
//            LogManager.shared.log("stopMonitoringSignificantLocationChanges\n")
//        }
//        
//    }
//    
//    private func logLocation(_ location: CLLocation, lastLocation: CLLocation?, address: String) {
//        var distance: Double = 0
//        if let lastLocation {
//            distance = location.distance(from: lastLocation)
//        }
//        LogManager.shared.log("location: [\(LogManager.shared.timeFormatter.string(from: location.timestamp)), \(location.coordinate.latitude), \(location.coordinate.longitude), \(Int(location.speed)), \(Int(location.horizontalAccuracy)), \(Int(distance)), \(address)]\n")
//    }
//    
//    private func adjustDistanceFilter(_ manager: CLLocationManager, location: CLLocation, lastLocation: CLLocation?) {
//        let oldDistanceFilter = manager.distanceFilter
//        if CMMotionActivityManager.isActivityAvailable() && CMMotionActivityManager.authorizationStatus() == .authorized {
//            activityManager.startActivityUpdates(to: .main) { [weak self] activity in
//                manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
//                var userActivityStatus = ""
//                if activity?.stationary == true {
//                    userActivityStatus = "静止"
//                    manager.distanceFilter = 40
//                    manager.activityType = .other
//                } else if activity?.walking == true {
//                    userActivityStatus = "步行"
//                    manager.distanceFilter = 40
//                    manager.activityType = .fitness
//                } else if activity?.running == true {
//                    userActivityStatus = "跑步"
//                    manager.distanceFilter = 80
//                    manager.activityType = .fitness
//                } else if activity?.cycling == true {
//                    userActivityStatus = "骑车"
//                    manager.distanceFilter = 100
//                    manager.activityType = .fitness
//                } else if activity?.automotive == true {
//                    userActivityStatus = "驾车"
//                    if let lastLocation = lastLocation {
//                        let distance = location.distance(from: lastLocation)
//                        let time = abs(location.timestamp.timeIntervalSince(lastLocation.timestamp))
//                        let speed = distance / time
//                        manager.distanceFilter = speed < 40 ? 150 : 1000
//                    } else {
//                        manager.distanceFilter = 150
//                    }
//                    manager.activityType = .automotiveNavigation
//                } else if activity?.unknown == true {
//                    userActivityStatus = "未知"
//                    manager.distanceFilter = 40
//                    manager.activityType = .other
//                } else {
//                    let userActivityType = self?.calculateUserActivity(location: location, lastLocation: lastLocation)
//                    manager.distanceFilter = userActivityType?.suggestedDistanceFilter ?? 40
//                    manager.activityType = .other
//                }
//                self?.activityManager.stopActivityUpdates()
//
//                LogManager.shared.log("--- 用户运动状态: \(userActivityStatus)\n")
//                LogManager.shared.log("++++1 distanceFilter--new: \(manager.distanceFilter), old-\(oldDistanceFilter)\n")
//            }
//        } else {
//            let userActivityType = calculateUserActivity(location: location, lastLocation: lastLocation)
//            manager.distanceFilter = userActivityType.suggestedDistanceFilter
//            
//            LogManager.shared.log("++++2 distanceFilter--new: \(manager.distanceFilter), old-\(oldDistanceFilter)\n")
//        }
//    }
//    
//    private func calculateUserActivity(location: CLLocation, lastLocation: CLLocation?) -> UserActivityType {
//        guard let lastLocation = lastLocation else { return .unknown }
//        let distance = location.distance(from: lastLocation)
//        let time = abs(location.timestamp.timeIntervalSince(lastLocation.timestamp))
//        let speed = distance / time
//        if speed < 0.2 { // 静止
//            return .stationary
//        } else if speed < 2 { // 人正常走路
//            return .walking
//        } else if speed < 3 { // 跑步
//            return .running
//        } else if speed < 5 { // 自行车
//            return .cycling
//        } else if speed < 10 { // 电动车，摩托车，公交
//            return .automotive
//        } else if speed < 40 { // 汽车
//            return .automotive
//        } else {
//            return .highSpeed // 超高速
//        }
//    }
//
//}
//
//
//// MARK: -  CLLocationManagerDelegate
//extension LocationManager: CLLocationManagerDelegate {
//    
//    //CLLocationManager定位代理方法
//    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//        guard let location = locations.last else { return }
//        
//        let lastLocation = self.database.getLastLocation()
//        self.database.save(location: location, horizontalAccuracy: location.horizontalAccuracy)
//        self.adjustDistanceFilter(manager, location: location, lastLocation: lastLocation)
//        
//        CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (pms, err) -> Void in
//            guard let newLocation = pms?.last?.location else { return }
//            var address: String = "未知"
//            if let placemark = pms?.last {
//                address = "\(placemark.locality ?? "")\(placemark.subLocality ?? "")\(placemark.name ?? "")"
//            }
//            self.logLocation(newLocation, lastLocation: lastLocation, address: address)
//        })
//    }
//    
//    public func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {
//        let arrivalDate = LogManager.shared.dateFormatter.string(from: visit.arrivalDate)
//        let departureDate = LogManager.shared.dateFormatter.string(from: visit.departureDate)
//        
//        LogManager.shared.log("到达时间: \(arrivalDate) 离开时间: \(departureDate) location: [\(visit.coordinate.latitude), \(visit.coordinate.longitude), \(Int(visit.horizontalAccuracy))]\n")
//    }
//    
//    // 当获取定位出错时调用
//    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
//        // 这里应该停止调用api
//        manager.stopUpdatingLocation()
//    }
//    
//    @available(iOS 14.0, *)
//    public func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
//        let newStatus = manager.authorizationStatus
//        if newStatus != lastAuthorizationStatus {
//            NotificationCenter.default.post(name: LocationManager.didChangeAuthorizationNotification, object: nil)
//            lastAuthorizationStatus = newStatus
//            if checkAndRequestAuthorization() {
//                startRequestLocation()
//            }
//        }
//    }
//    
//    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
//        let newStatus = status
//        if newStatus != lastAuthorizationStatus {
//            NotificationCenter.default.post(name: LocationManager.didChangeAuthorizationNotification, object: nil)
//            lastAuthorizationStatus = newStatus
//            if checkAndRequestAuthorization() {
//                startRequestLocation()
//            }
//        }
//    }
//}
//
//
//extension LocationManager {
//    
//    enum UserActivityType {
//        case unknown
//        case stationary
//        case walking
//        case running
//        case cycling
//        case automotive
//        case highSpeed
//        
//        var suggestedDistanceFilter: CLLocationDistance {
//            switch self {
//            case .unknown:
//                return 40
//            case .stationary:
//                return 40
//            case .walking:
//                return 40
//            case .running:
//                return 80
//            case .cycling:
//                return 100
//            case .automotive:
//                return 150
//            case .highSpeed:
//                return 1000
//            }
//        }
//    }
//}
